document.addEventListener("DOMContentLoaded", function () {
    // 通过 ID 选择特定的轮播图容器
    const banner = document.getElementById("banner");
    const ul = document.getElementById("carousel"); // 选择 id="carousel" 的 ul
    const images = ul.querySelectorAll("li"); // 获取所有图片
    const pageN = document.getElementById("pageN");
    const prevBtn = document.getElementById("prev");
    const nextBtn = document.getElementById("next");

    let currentIndex = 0;
    const totalImages = images.length;
    let interval;

    // 创建页码
    for (let i = 0; i < totalImages; i++) {
        const span = document.createElement("span");
        pageN.appendChild(span);
    }

    const dots = pageN.querySelectorAll("span");

    // 切换图片
    function updateSlider() {
        // 更新ul的transform
        ul.style.transform = `translateX(-${100 * currentIndex}vw)`;

        // 更新圆点的样式
        dots.forEach((dot, index) => {
            dot.classList.remove("active");
            if (index === currentIndex) {
                dot.classList.add("active");
            }
        });
    }

    // 自动切换图片
    function startAutoSlide() {
        interval = setInterval(() => {
            currentIndex = (currentIndex + 1) % totalImages;
            updateSlider();
        }, 4000);
    }

    // 停止自动切换
    function stopAutoSlide() {
        clearInterval(interval);
    }

    // 点击右按钮
    nextBtn.addEventListener("click", () => {
        currentIndex = (currentIndex + 1) % totalImages;
        updateSlider();
    });

    // 点击左按钮
    prevBtn.addEventListener("click", () => {
        currentIndex = (currentIndex - 1 + totalImages) % totalImages;
        updateSlider();
    });

    // 点击圆点
    dots.forEach((dot, index) => {
        dot.addEventListener("click", () => {
            currentIndex = index;
            updateSlider();
        });

        // 鼠标悬停事件
        dot.addEventListener("mouseover", () => {
            if (index !== currentIndex) {  // 如果不是当前的圆点
                dot.classList.add("hover");
            }
        });

        // 鼠标离开事件
        dot.addEventListener("mouseout", () => {
            dot.classList.remove("hover");
        });
    });

    // 鼠标悬浮停止自动播放
    banner.addEventListener("mouseenter", stopAutoSlide);
    banner.addEventListener("mouseleave", startAutoSlide);

    // 初始化
    updateSlider();
    startAutoSlide();
});